import 'package:flutter/material.dart';
import 'package:flutter_ducafecat_news/common/widgets/widgets.dart';
import 'package:flutter_ducafecat_news/pages/buytruck/buy_truck_view.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_ducafecat_news/base/base_mvp_presenter.dart';
import 'package:flutter_ducafecat_news/base/base_mvp_view.dart';
import 'package:flutter_ducafecat_news/base/base_mvp_widget.dart';
import 'package:flutter_ducafecat_news/common/entitys/home_newtruck_entity.dart';
import 'package:flutter_ducafecat_news/common/utils/utils.dart';
import 'package:flutter_ducafecat_news/common/widgets/dropdown/gzx_dropdown_header.dart';
import 'package:flutter_ducafecat_news/common/widgets/dropdown/gzx_dropdown_menu.dart';
import 'package:flutter_ducafecat_news/common/widgets/dropdown/gzx_dropdown_menu_controller.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'buy_truck_presenter.dart';

class SortCondition {
  String name;
  bool isSelected;
  SortCondition({this.name, this.isSelected});
}

class BuyTruckPage extends BaseWidget {
  @override
  BaseWidgetState<BasePresenter<BaseMvpView>, BaseWidget> getState() {
    // TODO: implement getState
    return _buyTruckState();
  }
}

class _buyTruckState extends BaseWidgetState<BuyTruckPresenter, BuyTruckPage>
    implements BuyTruckView {
  List<HomeNewtruckData> homeNewtruckDatas = [];
  List<String> _dropDownHeaderItemStrings = ['智能排序', '车型', '品牌', '价格', '更多'];
  List<SortCondition> _brandSortConditions = [];
  List<SortCondition> _distanceSortConditions = [];
  SortCondition _selectBrandSortCondition;
  SortCondition _selectDistanceSortCondition;
  GZXDropdownMenuController _dropdownMenuController =
      GZXDropdownMenuController();
  EasyRefreshController _controller = EasyRefreshController();
  var _scaffoldKey = new GlobalKey<ScaffoldState>();
  GlobalKey _stackKey = GlobalKey();
  @override
  Widget buildWidget(BuildContext context) {
    // TODO: implement buildWidget
    return Stack(
      key: _stackKey,
      children: <Widget>[
        Column(
          children: <Widget>[

            Container(
              height: getScreenHeight(context) -
                  getAppBarHeight(context) -
                  getTopBarHeight(context) -
                  106,
              child: EasyRefresh(
                controller: _controller,
                header: ClassicalHeader(),
                onRefresh: () async {
                  mPresenter.getTruckList();
                },
                onLoad: () async {
                  mPresenter.getTruckList();
                },
                child: SingleChildScrollView(
                  child: Column(
                    children: <Widget>[_buildListWidget()],
                  ),
                ),
              ),
            ),
          ],
        ),
        // 下拉菜单
        GZXDropDownMenu(
          // controller用于控制menu的显示或隐藏
          controller: _dropdownMenuController,
          // 下拉菜单显示或隐藏动画时长
          animationMilliseconds: 200,
          // 下拉菜单，高度自定义，你想显示什么就显示什么，完全由你决定，你只需要在选择后调用_dropdownMenuController.hide();即可
          menus: [
            GZXDropdownMenuBuilder(
                dropDownHeight: 40 * 8.0,
                dropDownWidget: _buildAddressWidget((selectValue) {
                  _dropDownHeaderItemStrings[0] = selectValue;
                  _dropdownMenuController.hide();
                  setState(() {});
                })),
            GZXDropdownMenuBuilder(
                dropDownHeight: 40 * 8.0,
                dropDownWidget:
                    _buildConditionListWidget(_brandSortConditions, (value) {
                  _selectBrandSortCondition = value;
                  _dropDownHeaderItemStrings[1] =
                      _selectBrandSortCondition.name == '全部'
                          ? '品牌'
                          : _selectBrandSortCondition.name;
                  _dropdownMenuController.hide();
                  setState(() {});
                })),
            GZXDropdownMenuBuilder(
                dropDownHeight: 40.0 * _distanceSortConditions.length,
                dropDownWidget:
                    _buildConditionListWidget(_distanceSortConditions, (value) {
                  _selectDistanceSortCondition = value;
                  _dropDownHeaderItemStrings[2] =
                      _selectDistanceSortCondition.name;
                  _dropdownMenuController.hide();
                  setState(() {});
                })),
          ],
        ),
      ],
    );
  }

  @override
  Widget buildHeaderWidget(BuildContext context) {
    // TODO: implement buildHeaderWidget
    return    // 下拉菜单头部
      GZXDropDownHeader(
        height: 50,
        // 下拉的头部项，目前每一项，只能自定义显示的文字、图标、图标大小修改
        items: [
          GZXDropDownHeaderItem(_dropDownHeaderItemStrings[0]),
          GZXDropDownHeaderItem(_dropDownHeaderItemStrings[1]),
          GZXDropDownHeaderItem(_dropDownHeaderItemStrings[2]),
          GZXDropDownHeaderItem(_dropDownHeaderItemStrings[3]),
          GZXDropDownHeaderItem(_dropDownHeaderItemStrings[4]),
        ],
        // GZXDropDownHeader对应第一父级Stack的key
        stackKey: _stackKey,
        // controller用于控制menu的显示或隐藏
        controller: _dropdownMenuController,
        // 当点击头部项的事件，在这里可以进行页面跳转或openEndDrawer
//              onItemTap: (index) {
//                if (index == 3) {
//                  _scaffoldKey.currentState.openEndDrawer();
//                }
//              },
      );
  }

  @override
  void initData() {
    // TODO: implement initData
    setAppBarText("首页");
    setOtherHeight(getBottomNavigationBarHeight(context));
    setEmptyWidgetVisible(true);
    _brandSortConditions.add(SortCondition(name: '全部', isSelected: true));
    _brandSortConditions.add(SortCondition(name: '金逸影城', isSelected: false));
    _brandSortConditions
        .add(SortCondition(name: '中影国际城我比较长，你看我选择后是怎么显示的', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '星美国际城', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '博纳国际城', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '大地影院', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '嘉禾影城', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '太平洋影城', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '万达影城', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '万达影城1', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '万达影城2', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '万达影城3', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '万达影城4', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '万达影城5', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '万达影城6', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '万达影城7', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '万达影城8', isSelected: false));
    _brandSortConditions.add(SortCondition(name: '万达影城9', isSelected: false));
    _selectBrandSortCondition = _brandSortConditions[0];

    _distanceSortConditions.add(SortCondition(name: '距离近', isSelected: true));
    _distanceSortConditions.add(SortCondition(name: '价格低', isSelected: false));
    _distanceSortConditions.add(SortCondition(name: '价格高', isSelected: false));

    _selectDistanceSortCondition = _distanceSortConditions[0];
  }

  Widget _buildListWidget() {
    return Container(
        child: Column(
      children: homeNewtruckDatas.map((item) {
        return Column(
          children: <Widget>[
            _buildListItemWidget(item),
            Divider(height: 1),
          ],
        );
      }).toList(),
    ));
  }

  Widget _buildListItemWidget(HomeNewtruckData homeNewtruckData) {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.all(25.h),
      child: Row(
        children: <Widget>[
          ImageCached(
            homeNewtruckData.imgThumbnail,
            width: 200,
            height: 150,
          ),
          SizedBox(
            width: 20.w,
          ),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Text(
                  homeNewtruckData.titleStr.split("\$\$")[0],
                  style: TextStyle(
                    fontSize: 30.sp,
                  ),
                  maxLines: 2,
                ),
                SizedBox(
                  height: 20.h,
                ),
                Text(homeNewtruckData.brandName,
                    style: TextStyle(fontSize: 26.sp, color: Colors.grey[400])),
                SizedBox(
                  height: 20.h,
                ),
                Row(
                  children: <Widget>[
                    Text(homeNewtruckData.price + "万",
                        style:
                            TextStyle(fontSize: 30.sp, color: Colors.red[400])),
                    Spacer(),
                    Container(
                        decoration: BoxDecoration(
                            color: Colors.deepOrangeAccent,
                            borderRadius:
                                BorderRadius.all(Radius.circular(15.w))),
                        padding: EdgeInsets.fromLTRB(10.w, 5.w, 10.w, 5.w),
                        child: Text(
                          "可议价",
                          style:
                              TextStyle(fontSize: 20.sp, color: Colors.white),
                        )),
                  ],
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  int _selectTempFirstLevelIndex = 0;
  int _selectFirstLevelIndex = 0;
  int _selectSecondLevelIndex = -1;

  _buildAddressWidget(void itemOnTap(String selectValue)) {
//    List firstLevels = new List<int>.filled(15, 0);
    List firstLevels = new List<String>.generate(15, (int index) {
      if (index == 0) {
        return '全部';
      }
      return '$index区';
    });

    List secondLevels = new List<String>.generate(15, (int index) {
      if (index == 0) {
        return '全部';
      }
      return '$_selectTempFirstLevelIndex$index街道办';
    });

    return Row(
      children: <Widget>[
        Container(
          width: 100,
          child: ListView(
            children: firstLevels.map((item) {
              int index = firstLevels.indexOf(item);
              return GestureDetector(
                onTap: () {
                  _selectTempFirstLevelIndex = index;

                  if (_selectTempFirstLevelIndex == 0) {
                    itemOnTap('全城');
                    return;
                  }
                  setState(() {});
                },
                child: Container(
                    height: 40,
                    color: _selectTempFirstLevelIndex == index
                        ? Colors.grey[200]
                        : Colors.white,
                    alignment: Alignment.center,
                    child: _selectTempFirstLevelIndex == index
                        ? Text(
                            '$item',
                            style: TextStyle(
                              color: Theme.of(context).primaryColor,
                            ),
                          )
                        : Text('$item')),
              );
            }).toList(),
          ),
        ),
        Expanded(
          child: Container(
            color: Colors.grey[200],
            child: _selectTempFirstLevelIndex == 0
                ? Container()
                : ListView(
                    children: secondLevels.map((item) {
                      int index = secondLevels.indexOf(item);
                      return GestureDetector(
                          onTap: () {
                            _selectSecondLevelIndex = index;
                            _selectFirstLevelIndex = _selectTempFirstLevelIndex;
                            if (_selectSecondLevelIndex == 0) {
                              itemOnTap(firstLevels[_selectFirstLevelIndex]);
                            } else {
                              itemOnTap(item);
                            }
                          },
                          child: Container(
                            height: 40,
                            alignment: Alignment.centerLeft,
                            child: Row(children: <Widget>[
                              SizedBox(
                                width: 20,
                              ),
                              _selectFirstLevelIndex ==
                                          _selectTempFirstLevelIndex &&
                                      _selectSecondLevelIndex == index
                                  ? Text(
                                      '$item',
                                      style: TextStyle(
                                        color: Theme.of(context).primaryColor,
                                      ),
                                    )
                                  : Text('$item'),
                            ]),
                          ));
                    }).toList(),
                  ),
          ),
        )
      ],
    );
  }

  _buildConditionListWidget(
      items, void itemOnTap(SortCondition sortCondition)) {
    return ListView.separated(
      shrinkWrap: true,
      scrollDirection: Axis.vertical,
      itemCount: items.length,
      // item 的个数
      separatorBuilder: (BuildContext context, int index) =>
          Divider(height: 1.0),
      // 添加分割线
      itemBuilder: (BuildContext context, int index) {
        SortCondition goodsSortCondition = items[index];
        return GestureDetector(
          onTap: () {
            for (var value in items) {
              value.isSelected = false;
            }
            goodsSortCondition.isSelected = true;

            itemOnTap(goodsSortCondition);
          },
          child: Container(
//            color: Colors.blue,
            height: 40,
            child: Row(
              children: <Widget>[
                SizedBox(
                  width: 16,
                ),
                Expanded(
                  child: Text(
                    goodsSortCondition.name,
                    style: TextStyle(
                      color: goodsSortCondition.isSelected
                          ? Theme.of(context).primaryColor
                          : Colors.black,
                    ),
                  ),
                ),
                goodsSortCondition.isSelected
                    ? Icon(
                        Icons.check,
                        color: Theme.of(context).primaryColor,
                        size: 16,
                      )
                    : SizedBox(),
                SizedBox(
                  width: 16,
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  @override
  BasePresenter<BaseMvpView> initPresenter() {
    // TODO: implement initPresenter
    return BuyTruckPresenter();
  }

  @override
  void showSuccess(data) {
    // TODO: implement showSuccess
  }

  @override
  void setTruckList(data) {
    // TODO: implement setTruckList
  }
}
